package org.thss.petri.gef.editparts;

import org.eclipse.draw2d.IFigure;
import org.eclipse.draw2d.PolygonDecoration;
import org.eclipse.draw2d.PolylineConnection;
import org.eclipse.emf.common.notify.Adapter;
import org.eclipse.emf.common.notify.Notification;
import org.eclipse.emf.common.notify.Notifier;
import org.eclipse.gef.EditPolicy;
import org.eclipse.gef.editparts.AbstractConnectionEditPart;
import org.thss.petri.gef.editparts.policies.ArcEditPolicy;
import org.thss.petri.gef.editparts.policies.ArcEndpointEditPolicy;
import org.thss.petri.gef.figures.ArcFigure;
import org.thss.petri.model.Arc;
import org.thss.petri.model.Node;
import org.thss.petri.model.PetriPackage;

public class ArcEditpart extends AbstractConnectionEditPart {
	
	private class ArcAdapter implements Adapter {

		@Override
		public void notifyChanged(Notification notification) {
			int id = notification.getFeatureID(PetriPackage.class);
			switch (id) {
			case PetriPackage.ARC__WEIGHT:
				refreshVisuals();
				break;
			}
		}

		@Override
		public Notifier getTarget() {
			return model;
		}

		@Override
		public void setTarget(Notifier newTarget) {
			if (newTarget == null) {
				return;
			}
			model = (Arc) newTarget;
			setModel(model);
		}

		@Override
		public boolean isAdapterForType(Object type) {
			return type.equals(getModel().getClass());
		}
		
	}
	
	private Arc model;
	private Adapter adapter;
	
	public ArcEditpart(Arc model) {
		this.model = model;
		setModel(model);
	}

	@Override
	protected void createEditPolicies() {
		installEditPolicy(EditPolicy.CONNECTION_ENDPOINTS_ROLE, new ArcEndpointEditPolicy());
		installEditPolicy(EditPolicy.CONNECTION_ROLE, new ArcEditPolicy());
	}

	@Override
	protected IFigure createFigure() {
		ArcFigure figure = new ArcFigure();
		return figure;
	}

	@Override
	protected void refreshVisuals() {
		Arc model = (Arc) getModel();
		ArcFigure figure = (ArcFigure) getFigure();
		figure.setWeight(model.getWeight());
	}

	@Override
	public void activate() {
		if (isActive()) {
			return;
		}
		super.activate();
		if (adapter == null) {
			adapter = new ArcAdapter();
		}
		((Notifier) getModel()).eAdapters().add(adapter);
	}

	@Override
	public void deactivate() {
		if (!isActive()) {
			return;
		}
		super.deactivate();
		if (adapter != null) {
			((Notifier) getModel()).eAdapters().remove(adapter);
		}
	}

	
}
